<?php

namespace App\Console\Commands;

use App\Models\GiveURewad;
use App\Models\Setting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

class UpdateAllLevel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'UpdateAllLevel';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新所有用户等级';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $condition = Setting::whereIn('key', ['level1_value', 'level2_value', 'level3_value', 'level4_value', 'level5_value', 'level6_value'])
            ->orderBy('id', 'asc')
            ->pluck('value');
        User::chunk(1000, function ($user_list) use ($condition) {
            foreach ($user_list as $user) {
                $user_ids = User::where('_lft', '>', $user->_lft)
                    ->where('_rgt', '<', $user->_rgt)
                    ->pluck('id');

                // 统计当天日收益
                $start = Carbon::now()->startOfDay()->subDay();
                $end = Carbon::now()->endOfDay()->subDay();
                $reward = GiveURewad::whereIn('user_id', $user_ids)->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('reward');

                if ($reward < $condition[0]) {
                    $level = '0';
                } elseif ($reward >= $condition[0] && $reward < $condition[1]) {
                    $level = '1';
                } elseif ($reward >= $condition[1] && $reward < $condition[2]) {
                    $level = '2';
                } elseif ($reward >= $condition[2] && $reward < $condition[3]) {
                    $level = '3';
                } elseif ($reward >= $condition[3] && $reward < $condition[4]) {
                    $level = '4';
                } elseif ($reward >= $condition[4] && $reward < $condition[5]) {
                    $level = '5';
                } elseif ($reward >= $condition[5]) {
                    $level = '6';
                }

                $user->vip_level = $level;
                $user->save();
            }
        });
    }
}
